<template>
  <div class="page-container relative">
    <DynamicForm class="mt-4" :config="dyConfig" :questions="dyQuestions" />
    <DynamicTable :tables="dyTable" :config="dyTableConfig" :icons="dyIcons" ref="fileRef">
      <!-- 面包屑 -->
      <template #title>
        <div>
          <a-breadcrumb>
            <template v-for="(item, index) in breadcrumbs" :key="index">
              <a-breadcrumb-item :class="index === breadcrumbs.length - 1 ? null : 'hierarchy'" @click="folderClick(item)">{{ item.name }}</a-breadcrumb-item>
            </template>
          </a-breadcrumb>
        </div>
      </template>
      <!-- 文件夹及文件-->
      <template #fileImg="{ record }">
        <img v-if="record.folder" class="w-11.5 h-11.5 cursor-pointer" @click="folderClick(record)" src="@/assets/img/fileImg/filePersonalFolder.png" alt="" />
      </template>
      <template #fileName="{ record }">
        <div>
          <p class="text-4 text-black text-opacity-65 cursor-pointer">
            <span v-if="record.folder" @click="folderClick(record)">{{ record.name }}</span>
            <span v-else @click="fileClick(record)">{{ record.name }}</span>
          </p>
          <!-- <p class="content space-x-2">
              <span v-if="record.code">{{ record.code }}</span>
              <span>{{ record.desc }}</span>
            </p> -->
        </div>
      </template>
      <template #size="{ record }">
        <div class="content">
          <!-- <p>{{ record.folder ? '文件夹' : record.suffix && record.suffix.toLocaleUpperCase() }}</p> -->
          <p>{{ changeByte(record.size) }}</p>
        </div>
      </template>
      <template #maxSize="{ record }">
        <div class="content">
          <!-- <p>容量上限</p> -->
          <p>{{ record.maxSize ? changeByte(record.maxSize) : '' }}</p>
        </div>
      </template>
      <!-- 只有根目录可以设置容量 -->
      <template v-if="[-1, 0].includes(state.level)" #setCapacity="{ record }">
        <div class="content">
          <span style="color: #409eff; cursor: pointer; font-size: 14px" @click="onSetCapacity(record)">设置</span>
        </div>
      </template>
    </DynamicTable>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, watch, getCurrentInstance, onBeforeUnmount, isRuntimeOnly } from 'vue';
import { DynamicForm, DynamicTable } from '@/components/public-template';
import { DYNAMICLAYERFORM, LOCALSUBSERVE, DYNAMICLAYERCLEAR, DYNAMICLOCALICONS } from '@/mixins/subject/subject-types';
import { Api, fileGetAllFolders, dirConfigGet, dirConfigSave, dirConfigBatchSave } from '@/config/api/fileInfo';
import indexService from './index.service';
import { changeByte, reviewFile } from '@/utils/common';
import { fileGetPreviewFileUrl as fileGetPerson } from '@/config/api/personFile';
import { fileGetPreviewFileUrl as fileGetProject } from '@/config/api/projectFile';
import { fileGetPreviewFileUrl as fileGetDept } from '@/config/api/deptFile';
import { getPreviewFileUrl as fileGetResource } from '@/config/api/resourceFileInfo';
import { filter } from 'rxjs/operators';
import { Modal, message } from 'ant-design-vue';

const state = reactive({
  treeData: [],
  showData: null,
  showType: '',
  level: 1
});
const fileRef = ref(null);
const breadcrumbs: any = ref([
  {
    id: '',
    name: '全部'
  }
]);
const dyConfig: any = {
  labelCol: 4,
  wrapperCol: 18,
  grid: 12, // 分栏
  style: 'table-form',
  cancelSave: true // 隐藏底部按钮
};
const dyLayerRef = ref(null);

const dyTableConfig: any = {
  name: 'deptFile',
  queryUrl: Api.fileQueryFolderWithFilePage,
  protType: 'post',
  isShowHeader: true,
  rowSelection: {
    type: 'checkbox'
  },
  params: { parentId: '' },
  beforeWithMethod: (data) => {
    data.forEach((item) => {
      delete item.children;
    });
    state.level = data[0]?.level;
    return data;
  }
};
const dyQuestions: any = reactive(indexService.getQuestions());
const dyTable: any = reactive(indexService.getTables(state.level));
const dyIcons: any = reactive(indexService.getIcons());
const { proxy }: any = getCurrentInstance();
const subscribeSubForm = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    try {
      if (item.key === LOCALSUBSERVE && item.state.name === layerConfig.name) {
        let params = {
          folderId: item.value.folderId,
          fileType: item.value.categorize,
          maxSize: item.value.maxSize,
          unit: item.value.unit
        };
        dirConfigSave(params).then((result) => {
          if (result.success) {
            message.success('提交成功');
            proxy.$NotificationPubSub.pushParams({ key: DYNAMICLAYERCLEAR });
            setTimeout(() => {
              fileRef.value.getData(params);
            }, 1000);
          }
        });
      } else if (item.key === LOCALSUBSERVE && item.state.name === dyLayerConfig.name) {
        paramsAll.value.forEach((obj) => {
          obj = Object.assign(obj, { unit: item.value.unit, maxSize: item.value.allMaxSize });
        });
        dirConfigBatchSave(paramsAll.value).then((res) => {
          if (res.success) {
            message.success('提交成功');
            proxy.$NotificationPubSub.pushParams({ key: DYNAMICLAYERCLEAR });
            setTimeout(() => {
              fileRef.value.getData(paramsAll.value);
            }, 1000);
          }
        });
      }
    } catch (error) {
      message.error(error);
    }
  });
const paramsAll: any = ref([]);
const subscribeSubIcon = proxy.$NotificationPubSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    try {
      if (item.key === DYNAMICLOCALICONS) {
        if (item.value.key === 'local' && item.value.state.name === 'setUp') {
          if (item.state.selected.length) {
            const dyLayerQuestions: any = reactive(indexService.getAllQuestions());
            proxy.$NotificationPubSub.pushParams({
              key: DYNAMICLAYERFORM,
              value: {
                config: dyLayerConfig,
                form: dyLayerQuestions
              }
            });
            paramsAll.value = [];
            item.state.selected.forEach((item) => {
              paramsAll.value.push({
                folderId: item.id,
                fileType: item.categorize
              });
            });
          } else {
            message.warning('请选中一项选项');
          }
        }
      }
    } catch (error) {
      message.error(error);
    }
  });

// 表格操作-容量上限弹层
const layerConfig: any = {
  name: 'onSetCapacity',
  width: '390px',
  portType: 'post',
  title: '设置',
  okText: '提交',
  type: 'layer',
  grid: 24,
  labelCol: 24,
  wrapperCol: 24,
  layout: 'vertical',
  localSub: true,
  params: {}
};
// 设置icon-容量上限弹层
const dyLayerConfig: any = {
  name: 'onAllSetCapacity',
  width: '390px',
  title: '设置',
  okText: '提交',
  type: 'layer',
  grid: 24,
  labelCol: 24,
  wrapperCol: 24,
  layout: 'vertical',
  localSub: true
};
async function onSetCapacity(record) {
  let params = {
    type: record.categorize,
    folderId: record.id
  };
  const result = await dirConfigGet(params).catch(() => {});
  let maxSize = result.data.maxSize;
  let fileType = result.data.fileType;
  let folderId = record.id;
  let unit = result.data.unit || 'GB';
  // 接受返回的数据中maxSize没变 改
  let layerQuestions: any = reactive(indexService.getSetQuestions(maxSize, fileType, folderId, unit));
  proxy.$NotificationPubSub.pushParams({
    key: DYNAMICLAYERFORM,
    value: {
      config: layerConfig,
      form: layerQuestions
    }
  });
}

watch(
  () => state.level,
  (newVal) => {
    // 隐藏上方设置按钮
    dyIcons.forEach((item) => {
      item.hidden = [{ key: 'level', value: true }];
      item.hidden = state.level !== 0 ? true : false;
    });
    // 第三次层级不允许出现设置
    // dyTable.forEach((item) => {
    //   if (item.key == 'actions') {
    //     item.handle.forEach((frItem) => {
    //       frItem?.showKey = [{ key: 'level', value: true }];
    //     });
    //   }
    // });
  },
  { immediate: true }
);

getFolderTree();
// 获取项目文件目录
function getFolderTree() {
  fileGetAllFolders({ name: '' }).then((result) => {
    if (result.success) {
      state.treeData = result.data;
    }
  });
}

// 点击文件夹
function folderClick(node) {
  // table传参
  dyTableConfig.params.parentId = node.id;
  fileRef.value.getData();
  let flag = true;
  breadcrumbs.value.forEach((item, index) => {
    if (item?.id === node.id) {
      breadcrumbs.value.splice(index + 1);
      flag = false;
    }
  });
  if (flag) {
    breadcrumbs.value.push({
      id: node.id,
      name: node.name
    });
  }
}

// 面包屑
function breadcrumb(arr: any, key: any, finalData: Array<any> = []) {
  for (let i = 0, len = arr.length; i < len; i++) {
    finalData.push({ name: arr[i].name, id: arr[i].id });
    if (arr[i].id === key) {
      return finalData;
    } else if (arr[i].children && arr[i].children.length >= 1) {
      if (breadcrumb(arr[i].children, key, finalData) != false) return finalData;
    }
    finalData.pop();
  }
  return false;
}

// 点击文件
function fileClick(node) {
  let fun;
  // 文件归类 1=个人,2=项目,3= 部门 ,4=资源文件,5=档案文件,6=公共文件
  switch (node.categorize) {
    case 1:
      fun = fileGetPerson;
      break;
    case 2:
      fun = fileGetProject;
      break;
    case 3:
      fun = fileGetDept;
      break;
    case 4:
      fun = fileGetResource;
      break;
    default:
      break;
  }
  const params = { id: node.id, expires: 2, timeUnit: 'HOURS' };
  fun(params).then((res) => {
    if (res.success && res.data) {
      reviewFile(res.data);
    }
  });
}

onBeforeUnmount(() => {
  subscribeSubForm && subscribeSubForm.unsubscribe();
  subscribeSubIcon && subscribeSubIcon.unsubscribe();
  proxy.$NotificationPubSub.clearParams();
  proxy.$NotificationFormSub.clearParams();
});
</script>

<style lang="less" scoped>
:deep(.tree-warpper) {
  .ant-tree-switcher {
    line-height: 36px;
  }
  .ant-tree-node-content-wrapper {
    min-height: 36px;
    line-height: 36px;
    &.ant-tree-node-selected {
      background-color: #e5eefd;
      color: #005aea;
    }
  }
}
.content {
  @apply text-black text-opacity-45;
  p:nth-child(2) {
    display: inline-block;
  }
}
.hierarchy {
  cursor: pointer;
}
.hierarchy:hover {
  color: #409eff;
}
</style>
